package com.oswift.utils.common;

import java.io.Closeable;
import java.io.IOException;
import java.net.HttpURLConnection;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 *
 * I/O stream的帮助类，提供流关闭等方法
 *
 * @author zhuou
 * @version C03 Oct 27, 2012
 * @since OSwift GPM V1.0
 */
public final class StreamUtil
{

    /**
     * 日志实例
     */
    private static Logger log = LoggerFactory.getLogger(StreamUtil.class);

    /**
     * 类StreamUtil的实例
     */
    private static StreamUtil instance = new StreamUtil();

    /**
     * 构造函数
     */
    private StreamUtil()
    {
    }

    /**
     * 获取类StreamUtil的实例
     *
     * @return 类StreamUtil的实例
     */
    public static StreamUtil getInstance()
    {
        return instance;
    }

    /**
     * 关闭流
     *
     * @param streams
     *            待关闭的流对象，可以使用数组或多参数的方式传入多个参数值
     */
    public void close(Closeable... streams)
    {
        if ((null == streams) || (streams.length == 0))
        {
            return;
        }

        for (int i = 0; i < streams.length; i++)
        {
            if (null == streams[i])
            {
                continue;
            }

            try
            {
                streams[i].close();
            }
            catch (IOException e)
            {
                // 忽略
                log.debug("Failed to close the stream.", e);
            }
        }
    }

    /**
     * 关闭HTTP连接
     *
     * @param urlConnection
     *            HTTP连接实例
     */
    public void disconnect(HttpURLConnection urlConnection)
    {
        if (null == urlConnection)
        {
            return;
        }

        urlConnection.disconnect();
    }
}
